package com.ajouroid.smartcoworker;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.provider.MediaStore.Images;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

public class RegisterActivity extends Activity {

	EditText et_id;
	EditText et_pwd;
	EditText et_name;
	EditText et_email;
	Button btn_register;
	Button btn_img_upload;
	ImageView img_profile;
	String strCur_time;
	static int REQUEST_CAMERA = 1;
	static int REQUEST_GALLERY = 2;
	static String IMG_FILEPATH = null;
	final String[] items = {"Upload from Camera", "Upload from Gallery"};


	
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);
        
        et_id = (EditText)findViewById(R.id.reg_id);
        et_pwd = (EditText)findViewById(R.id.reg_pwd);
        et_name = (EditText)findViewById(R.id.reg_name);
        et_email = (EditText)findViewById(R.id.reg_email);
        
        btn_register = (Button)findViewById(R.id.reg_register);
        btn_img_upload = (Button)findViewById(R.id.reg_btn_img_upload);
        img_profile = (ImageView)findViewById(R.id.reg_profile_img);
        
        long timestamp = System.currentTimeMillis();
        SimpleDateFormat sdfTime = new SimpleDateFormat("yyyyMMddHHmmss");
        strCur_time = sdfTime.format(new Date(timestamp));
    }
    
    @Override
    public void onResume()
    {
    	super.onResume();
    	
    	
    	
    	btn_img_upload.setOnClickListener(new OnClickListener() {
			
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				AlertDialog.Builder builder = new AlertDialog.Builder(RegisterActivity.this);
				builder.setTitle("Select mode");
				builder.setItems(items, new DialogInterface.OnClickListener() {
				    public void onClick(DialogInterface dialog, int pos) {
				        if(pos == 0){
				        	takeCamera();
				        }
				        else{
				        	takeGallery();
				        }
				    }
				});
				AlertDialog alert = builder.create();
				alert.show();
			}
		});
    	
    	btn_register.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				RegisterTask task = new RegisterTask(RegisterActivity.this);
				
				String id = et_id.getText().toString();
				String pwd = et_pwd.getText().toString();
				String name = et_name.getText().toString();
				String email = et_email.getText().toString();
				String image = IMG_FILEPATH;
								
				task.execute(id,pwd,name,email,image);
			}
    		
    	});
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_register, menu);
        return true;
    }
    
    //사진 촬영
  	public void takeCamera() {
  		//카메라 호출 intent 생성
  		Intent intent = new Intent();
  		intent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);

  		startActivityForResult(intent, REQUEST_CAMERA);
  	}
  	
  	//사진 불러오기
  	public void takeGallery() {
  		//gallery 호출 intent 생성
  		Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
  		intent.setType("image/*");
  		startActivityForResult(Intent.createChooser(intent, "Select Picture"),REQUEST_GALLERY);
  	}
  	
  	@SuppressWarnings("deprecation")
	@Override
  	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
  		// TODO Auto-generated method stub
  		super.onActivityResult(requestCode, resultCode, data);
  		
  		if(resultCode != RESULT_OK)
  			return;
  		
  		if(requestCode == REQUEST_CAMERA) {
  			
  			Bitmap bm = (Bitmap) data.getExtras().get("data");
  			
  			String dir = Environment.getExternalStorageDirectory() + "/SmartCoworker";
  			File copyFile = new File(dir);
  			if (!copyFile.isDirectory()){
  				copyFile.mkdir();
  	  		}
  			copyFile = new File(dir + "/" + strCur_time + ".jpeg");
  			OutputStream out = null;
  			try {
  			            
  			    copyFile.createNewFile();
  			    out = new FileOutputStream(copyFile);
  			    if ( bm.compress(CompressFormat.JPEG, 100, out) );
  			            
  			    } catch (Exception e) {         
  			    e.printStackTrace();
  			    } finally {
  			         try {
  			             out.close();
  			         } catch (IOException e) {
  			             e.printStackTrace();
  			    }
  			}
  			BitmapFactory.Options option = new BitmapFactory.Options();
  	  		option.inSampleSize = 4;
  	  		Bitmap orgImage = BitmapFactory.decodeFile(copyFile.getAbsolutePath(), option);
  	  		Bitmap resize = Bitmap.createScaledBitmap(orgImage, 130, 150, true);
  			img_profile.setImageBitmap(resize);
  			IMG_FILEPATH = copyFile.toString();
  			Toast.makeText(this, IMG_FILEPATH, Toast.LENGTH_SHORT).show();
  		}
  		
  		if(requestCode == REQUEST_GALLERY) {
  			
			try {
				BitmapFactory.Options option = new BitmapFactory.Options();
	  	  		option.inSampleSize = 4;
	  	  		Bitmap orgImage;
				orgImage = Images.Media.getBitmap(getContentResolver(), data.getData());
				Bitmap resize = Bitmap.createScaledBitmap(orgImage, 130, 150, true);
				img_profile.setImageBitmap(resize);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				img_profile.setImageResource(R.drawable.anonymous);
				Toast.makeText(getApplicationContext(), "File is not found!!", Toast.LENGTH_SHORT).show();
			}
			String[] proj = { MediaStore.Images.Media.DATA };
			Cursor cursor = managedQuery(data.getData(), proj, null, null, null);
			int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
			cursor.moveToFirst();
			String imgPath = cursor.getString(column_index);
			IMG_FILEPATH = imgPath;
			Toast.makeText(this, IMG_FILEPATH, Toast.LENGTH_SHORT).show();
  			//img_profile.setImageURI(data.getData());
  		}
  	}

    public class RegisterTask extends AsyncTask<String, Void, String>
    {
    	Context mCtx;
    	ProgressDialog regist;
    	public RegisterTask(Context context)
    	{
    		mCtx = context;
    	}
    	
		@Override
		protected String doInBackground(String... arg) {
			HttpConnector conn = new HttpConnector();
			
			/*
			Map<String, String> msg = new HashMap<String,String>();
			msg.put("type", "register");
			msg.put("id", arg[0]);
			msg.put("password", arg[1]);
			msg.put("name", arg[2]);
			msg.put("email", arg[3]);
			
			String resp = conn.post("Login", msg);
			*/
			String id = arg[0];
			String password = arg[1];
			String name = arg[2];
			String email = arg[3];
			String image = arg[4];
			
			String resp = conn.register(id, password, name, email, image);
			return resp;
		}

		@Override
		protected void onPostExecute(String result) {			
			try {
				JSONObject obj = new JSONObject(result);
				String status = obj.getString("status");
				
				if (status.equals("ok"))
				{
					Toast.makeText(mCtx, "Register Successful.", Toast.LENGTH_SHORT).show();
					finish();
				}
				else if (status.equals("duplicate"))
				{
					Toast.makeText(mCtx, "Duplicated ID.", Toast.LENGTH_SHORT).show();
				}
				else
				{
					Toast.makeText(mCtx, "Error: " + status, Toast.LENGTH_SHORT).show();
				}
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			regist.dismiss();
			super.onPostExecute(result);
		}

		@Override
		protected void onPreExecute() {
			regist = new ProgressDialog(mCtx);
			regist.setTitle("Wait please...");
			regist.setMessage("Uploading the file...");
			regist.setCancelable(false);
			regist.setProgressStyle(ProgressDialog.STYLE_SPINNER);
			
			regist.show();
			
			super.onPreExecute();
		}    	
    }
}
